﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
namespace PM.Code.Web
{
    /// <summary>
    /// 将控件（datagrid、datatable等）数据导出到excel中
    /// </summary>
    public class output
    {
        public output()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        /// <summary>
        /// 将dataset中的内容输出到excel或xml中
        /// </summary>
        /// <param name="ds">DataSet控件</param>
        /// <param name="typeid">输出类型（1是excel，2是xml）</param>
        /// <param name="filename">输出文件名</param>
        public static void DataSetToExcel(DataSet ds, string typeid, string filename)
        {
            HttpResponse resp;
            resp = System.Web.HttpContext.Current.Response;
            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
            string colHeaders = "", ls_item = "";
            int i = 0;

            //定义表对象与行对像，同时用DataSet对其值进行初始化 
            DataTable dt = ds.Tables[0];
            DataRow[] myRow = dt.Select("");
            // typeid=="1"时导出为EXCEL格式文件；typeid=="2"时导出为XML格式文件 
            if (typeid == "1")
            {
                //取得数据表各列标题，各标题之间以\t分割，最后一个列标题后加回车符 
                for (i = 0; i < dt.Columns.Count-1; i++)
                    colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                colHeaders += dt.Columns[i].Caption.ToString() + "\n";
                //向HTTP输出流中写入取得的数据信息 
                resp.Write(colHeaders);
                //逐行处理数据   
                foreach (DataRow row in myRow)
                {
                    //在当前行中，逐列获得数据，数据之间以\t分割，结束时加回车符\n 
                    for (i = 0; i < row.Table.Columns.Count - 1; i++)
                        ls_item += row[i].ToString() + "\t";
                    ls_item += row[i].ToString() + "\n";
                    //当前行数据写入HTTP输出流，并且置空ls_item以便下行数据     
                    resp.Write(ls_item);
                    ls_item = "";
                }
            }
            else
            {
                if (typeid == "2")
                {
                    //从DataSet中直接导出XML数据并且写到HTTP输出流中 
                    resp.Write(ds.GetXml());
                }
            }
            //写缓冲区中的数据到HTTP头文件中 
            resp.End();
        }

        /// <summary>
        /// 将控件（datagrid,gridview）中数据输出到xml中(不支持部分载入)
        /// </summary>
        /// <param name="ctl">控件（datagrid,gridview）</param>
        /// <param name="filename">输出文件名</param>
        public static void ControlToExcel(System.Web.UI.Control ctl, string filename)
        {
            StringBuilder sb = new StringBuilder();
            System.IO.StringWriter sw = new System.IO.StringWriter(sb);
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            Page page = new Page();
            HtmlForm form = new HtmlForm();
            ctl.EnableViewState = false;
            page.EnableEventValidation = false;
            page.DesignerInitialize();
            page.Controls.Add(form);
            form.Controls.Add(ctl);

            page.RenderControl(htw);

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
            HttpContext.Current.Response.Charset = "UTF-8";
            HttpContext.Current.Response.ContentEncoding = Encoding.Default;
            HttpContext.Current.Response.Write(sb.ToString());
            HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 将DataTable 导出到Excel
        /// </summary>
        /// <param name="table">DataTable</param>
        /// <param name="header">表头名</param>
        public static void DataTableToExcel(DataTable table,string header)
        {
            StringBuilder sbText = new StringBuilder();
            try
            {
                sbText.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=gb2312\">");
                sbText.AppendLine("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");
                //添加表头名
                sbText.AppendFormat("<tr><th colspan='{0}'>{1}</tr>",table.Columns.Count.ToString(),header);
                //导出列名
                sbText.AppendLine("<tr style=\"font-weight:bold;background-color:#afb4db;white-space:nowrap;\">");
                for (int i = 0; i < table.Columns.Count; i++)
                {
                    sbText.AppendFormat("<td>{0}</td>", table.Columns[i].ColumnName);
                }
                sbText.AppendLine("</tr>");
                //导出数据 
                foreach (DataRow row in table.Rows)
                {
                    sbText.Append("<tr>");
                    for (int i = 0; i < table.Columns.Count; i++)
                    {
                        sbText.AppendFormat("<td>{0}</td>", row[i]);
                    }
                    sbText.AppendLine("</tr>");
                }
                sbText.AppendLine("</table>");
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.Charset = "GB2312";
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xls");
                //设置输出流编码格式
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                //设置输出文件类型为excel文件。
                HttpContext.Current.Response.ContentType = "application/ms-excel";
                //EnableViewState = false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            HttpContext.Current.Response.Write(sbText.ToString());
            HttpContext.Current.Response.End();
        }
    }
}
